package com.lnsoft.cac.server;

import com.lnsoft.cac.server.handle.HandleFactory;
import com.lnsoft.cac.server.handle.codec.Device;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CACChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger logger = LoggerFactory.getLogger(CACChannelInitializer.class);

    @Autowired
    private HandleFactory handleFactory;

    @Value("${netty.server.heartBeatIdleTime}")
    private int heartBeatIdleTime;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        //  初始化监测仪的信息，和监测仪和cac的会话信息；
        Device device = new Device();
        device.setLastHeartBeatTime(System.currentTimeMillis());
        device.setHeatBeatIdleTime(heartBeatIdleTime);

        device.setChannelId(ch.id());
        device.setServerPort(ch.localAddress().getPort());
        logger.debug("NioServiceSocketChannle#initChannel");
        ChannelPipeline pipeline = ch.pipeline();
        // 心跳检测
//        pipeline.addLast("IdleStateHandler",new IdleStateHandler(heartBeatIdleTime,0,0));
        // 心跳检测自定义处理
//        pipeline.addLast("HeartBeatServerHandle",handleFactory.createHeartBeatServerHandle(device));

        pipeline.addLast("CACDecoder",handleFactory.createCacDecoder());
        pipeline.addLast("CACEncoder",handleFactory.createCacEncoder());

        pipeline.addLast("CACChannelHandle",handleFactory.createCacChannelHandle(device));
    }
}